import 'dotenv/config'
import express from 'express'
import fetch from 'node-fetch'
// import puppeteer from 'puppeteer' // 注释掉
import fs from 'fs'
import path from 'path'

// let garminCookies = '' // 注释掉

// // 自动登录并获取 Cookie
// async function loginAndGetCookies() {
//     // const browser = await puppeteer.launch({ headless: false });
//     const browser = await puppeteer.launch({
//       executablePath: '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'
//     });
//     const page = await browser.newPage();
//     await page.goto('https://sso.garmin.cn/portal/sso/en-US/sign-in?clientId=GarminConnect&service=https%3A%2F%2Fconnect.garmin.cn%2Fmodern', {
//         waitUntil: 'networkidle2'
//     });
//     await page.waitForSelector('input[name="email"]', { timeout: 10000 });
//     await page.type('input[name="email"]', process.env.GARMIN_USER);
//     await page.type('input[name="password"]', process.env.GARMIN_PASS);
//     await page.click('button[type="submit"]');
//     await page.waitForNavigation({ waitUntil: 'networkidle2' });

//     // 获取登录后的 Cookie
//     console.log('登录成功，获取 Cookie...', page);
//     const cookies = await page.cookies();
//     garminCookies = cookies.map(c => `${c.name}=${c.value}`).join('; ');
//     await browser.close();
// }

// // 启动时先登录一次
// await loginAndGetCookies()

const app = express()
const PORT = 3000

app.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', 'http://localhost:5173')
    res.header('Access-Control-Allow-Credentials', 'true')
    res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization')
    res.header('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE,OPTIONS')
    if (req.method === 'OPTIONS') {
        return res.sendStatus(200)
    }
    next()
})

app.get('/api/activity/:id', async (req, res) => {
  const { id } = req.params
  console.log(`Fetching activity with ID: ${id}`)
  // console.log('garminCookies:', garminCookies)
  try {
    // 直接读取本地 mock_json/{id}.json 并返回
    const mockPath = path.resolve(process.cwd(), 'mock_json', `${id}.json`)
    if (fs.existsSync(mockPath)) {
      const mockData = fs.readFileSync(mockPath, 'utf-8')
      res.setHeader('Content-Type', 'application/json')
      return res.status(200).send(mockData)
    } else {
      return res.status(403).json({ error: '未找到本地 mock 数据' })
    }
  } catch (err) {
    res.status(500).json({ error: '服务器错误', detail: err.message })
  }
})

app.listen(PORT, () => {
  console.log(`Proxy server running at http://localhost:${PORT}`)
})